package com.lbj.mvvm.base

import android.os.Bundle
import android.os.PersistableBundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.lbj.mvvm.helper.VMFactory
import com.lbj.mvvm.helper.getVMClazz

abstract class JetpackVMActivity<VM : JetpackVM> : AppCompatActivity() {

    lateinit var VM: VM

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(layoutId())
        VM = createVM()
        registerDefUIChange()
        initStart()
    }

    abstract fun layoutId(): Int
    abstract fun initStart()
    abstract fun showLoading(message:String = "请求网络中...")
    abstract fun dismissLoading()

    private fun createVM():VM = ViewModelProvider(this,VMFactory())[getVMClazz(VM)]

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        VM.defUI.showDialog.observe(this, Observer {
            showLoading(if(it.isEmpty()) {
                "请求网络中..."
            } else it)
        })
        VM.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })
    }
}